﻿using OpenTK.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace testopenTk
{
    public static class Shader
    {
        public static int SProgram = 0;
        //位置，贴图，法向，模视矩阵，
        public static int vPosition = 0, vTexCoord = 0, vNormal = 0,
            ModelView = 0, Projection = 0, AmbientProduct=0, DiffuseProduct = 0, SpecularProduct=0,
            SelectColor=0,bOnlyColor=0,Camera=-1,Emission=0,LightOn=0,Shininess=0
            , LightPosition=0;
        internal static int bOnlyShadow=0;
        internal static int bOnlyTexture=0;

        public static int InitShader(string vertexSL, string fragSL)
        {
            int program = GL.CreateProgram();
            if (!InitOne(vertexSL, program, ShaderType.VertexShader))
                return 0;
            if (!InitOne(fragSL, program, ShaderType.FragmentShader))
                return 0;
            GL.LinkProgram(program);
            int link = 0;
            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out link);
            if (link==0)
            {
                string info = "";
                GL.GetProgramInfoLog(program, out info);
                MyMessage.show("shader链接错误:"+info);
                return 0;
            }
          
            return program;
        }
        static bool InitOne(string myString,int program,ShaderType shadertype)
        {
            if (!File.Exists(myString))
            {
                MyMessage.show(myString+"不存在");
                return false;
            }
            using (StreamReader sr = new StreamReader(myString))
            {
                myString = sr.ReadToEnd();
                if (myString == "")
                {
                    MyMessage.show("shader文件为空");
                    return false;
                }
            }
            
            int Shader = GL.CreateShader(shadertype);
            GL.ShaderSource(Shader, myString);
            GL.CompileShader(Shader);
            int temp = 0;
            GL.GetShader(Shader, ShaderParameter.CompileStatus, out temp);
            if (temp == 0)
            { 
                string s = "";
                GL.GetShaderInfoLog(Shader, out s);
                MyMessage.show("Shader加载错误：" + s + Environment.NewLine + "即将关闭程序");
                return false;
            }
            GL.AttachShader(program, Shader);
            return true;
        }
    }
}